﻿#include "CameraAdapter.h"
#include "ui_CameraAdapter.h"
#include<QCameraInfo>
#include<QList>
#include<QFile>
#include"kits/Config.h"


CameraAdapter::CameraAdapter(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CameraAdapter)
{
    ui->setupUi(this);
}

CameraAdapter::~CameraAdapter()
{
    closeCamera();
    delete ui;
}

void CameraAdapter::closeCamera()const
{
    if(!mCamera->isAvailable()) return;
    mCamera->stop();
}
//打开摄像头,如果指定摄像头就打开指定摄像头，没有指定就打开默认摄像头
void CameraAdapter::openCamera(const QString &description)
{
    QCameraInfo info = QCameraInfo::defaultCamera();
    if(!description.isEmpty()){
        QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
        foreach (const QCameraInfo &cameraInfo, cameras){
            if(cameraInfo.description() == description){
                info = cameraInfo;
                break;
            }
        }
    }
    mCamera = new QCamera(info,this);
//定义编译选项在camera.pri里面,定义CAMERA_VIEW_SHOW表示通过取景器方式显示，没有定义表示通过图片方式显示
#ifdef CAMERA_VIEW_SHOW
    mViewfinder = new QCameraViewfinder(ui->lab_view1);
    mViewfinder->resize(ui->lab_view1->size());
    mViewfinder->setAspectRatioMode(Qt::KeepAspectRatio);//设置全视角显示
    mCamera->setViewfinder(mViewfinder);
    mViewfinder->show();
#elif
    mImageCapture = new QCameraImageCapture(mCamera);
    mImageCapture->setCaptureDestination(QCameraImageCapture::CaptureToBuffer);
    connect(mImageCapture,SIGNAL(imageCaptured(int,QImage)),SLOT(onImageCaptured(int,QImage)));
#ifdef WIN32
    connect(mImageCapture,SIGNAL(imageSaved(int,QString)),SLOT(onImageSaved(int,QString)));
#endif
#endif
    mCamera->start();
}
//枚举摄像头
void CameraAdapter::enumCamera()
{
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    foreach (const QCameraInfo &cameraInfo, cameras){
        xPrint<<cameraInfo.deviceName()<<cameraInfo.description();
    }
}

void CameraAdapter::onImageCaptured(int id, QImage img)
{
     Q_UNUSED(id)
    ui->lab_view1->setPixmap(QPixmap::fromImage(img).scaled(ui->lab_view1->size()));
    ui->lab_view2->setPixmap(QPixmap::fromImage(img).scaled(ui->lab_view2->size()));
}

//windows平台下截图默认保存图片，设置setCaptureDestination(QCameraImageCapture::CaptureToBuffer);也无效只能手动删除了
void CameraAdapter::onImageSaved(int id, const QString &fileName)
{
    Q_UNUSED(id)
    QFile::remove(fileName);

}
